package com.anmong.cloud.cloudadmin.common.config;


import com.anmong.cloud.cloudadmin.common.filter.RepeatedlyReadRequestWrapper;
import com.anmong.cloud.cloudapi.entity.Permission;
import com.anmong.cloud.cloudapi.mapper.PermissionMapper;
import com.anmong.cloud.cloudcommon.constant.CommonEnum;
import com.anmong.cloud.cloudcommon.exception.ForbiddenException;
import com.anmong.cloud.cloudcommon.util.IpUtil;
import com.anmong.cloud.cloudcommon.util.ServletUtil;
import com.anmong.cloud.mq.constant.HttpEnum;
import com.anmong.cloud.mq.constant.MqEnum;
import com.anmong.cloud.mq.dto.SysOperateLogDTO;
import com.anmong.cloud.mq.rocketmq.MqSimpleProducer;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;

import static org.springframework.http.MediaType.APPLICATION_JSON;

@Component
@Slf4j
public class CloudHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private MqSimpleProducer mqSimpleProducer;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 登录认证检查，鉴权，
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler){
        //System.out.println("==preHandle=="+handler.getClass().getName());
        LocalDateTime now = LocalDateTime.now();
        SysOperateLogDTO dto = new SysOperateLogDTO();
        dto.setCreateTime(now);
        dto.setUpdateTime(now);
        String contextPath = request.getContextPath();
        String url = contextPath + request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
        dto.setUrl(url);
        String requestId = request.getHeader(HttpEnum.Header.请求ID.code);
        dto.setRequestId(requestId);
        dto.setMethod(request.getMethod());
        dto.setIpAddress(IpUtil.getIpAddress(request));
        dto.setStatusCode(response.getStatus());
        String parameter = null;
        if (StringUtils.isNotEmpty(request.getContentType()) && APPLICATION_JSON.toString().equals(request.getContentType())){
            RepeatedlyReadRequestWrapper requestWrapper;
            if (request instanceof RepeatedlyReadRequestWrapper) {
                requestWrapper = (RepeatedlyReadRequestWrapper) request;
                parameter = requestWrapper.getBody();
            }
        }
        //contentType为x-www-form-urlencoded的直接从parameterMap取参数
        else {
            parameter = ServletUtil.getUrlParamsByMap(request.getParameterMap());
        }
        dto.setParameter(parameter);
        String token = request.getHeader(HttpEnum.Header.认证TOKEN.code);
        if (StringUtils.isBlank(token)) {
            dto.setAuthToken(token);
        }
        else {
            dto.setIsAuth(CommonEnum.Is.否.code);
        }
        Permission permission = permissionMapper.selectOne(new QueryWrapper<Permission>()
                .eq("url",url)
        );
        if (permission != null){
            dto.setInterfaceName(permission.getName());
           /* if (!StringUtils.equals(url,permission.getUrl())){
               throw new ForbiddenException("您没有权限操作!");
            }*/
        }
        //异步mq记录操作日志
        try {
            mqSimpleProducer.sendAsyncOrderlyMsgWithTag(MqEnum.Topic.日志.code,MqEnum.Tag.后台操作日志.code
                    ,objectMapper.writeValueAsString(dto),String.valueOf(this.hashCode()));
        }
        catch (JsonProcessingException e){
            log.error("preHandler中json解析出错:{}",e.getMessage(),e);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==postHandle=="+handler.getClass().getName());
    }

    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response,
                                Object handler, Exception ex)throws Exception {
        //System.out.println("==afterCompletion=="+handler.getClass().getName());
    }

}
